package com.mvc.interceptor;

import com.spring.annotation.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * 跨域访问拦截器
 */
public class CorsInterceptor implements HandlerInterceptor{
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		if(request.getMethod().equals("OPTIONS")){
			response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
			response.setHeader("Access-Control-Request-Method", "GET, POST, OPTIONS");
			response.setHeader("Access-Control-Request-Headers", "Cookie");
			response.setHeader("Access-Control-Max-Age", "7200");
			response.setHeader("Access-Control-Allow-Credentials", "true");
			response.setHeader("Access-Control-Allow-Headers", "Content-Type, Cookie");
			
			// 预检请求直接响应回去，不用走后面的了
			return false;
		}
		
		
		// 简单请求还是得走下后续的拦截器放行
		if (request.getHeader("Origin") != null) {
			response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
			response.setHeader("Access-Control-Allow-Credentials", "true");
			response.setHeader("Access-Control-Allow-Headers", "Content-Type, Cookie");
		}
		return true;
	}
}
